home *** CD-ROM | disk | FTP | other *** search
/ Windows Game Programming for Dummies (2nd Edition) / WinGamProgFD.iso / pc / DirectX SDK / DXSDK / samples / Multimedia / DirectShow / BaseClasses / refclock.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2001-10-08  |  10.5 KB  |  309 lines

  1. //------------------------------------------------------------------------------
  2. // File: RefClock.cpp
  3. //
  4. // Desc: DirectShow base classes - implements the IReferenceClock interface.
  5. //
  6. // Copyright (c) 1992-2001 Microsoft Corporation.  All rights reserved.
  7. //------------------------------------------------------------------------------
  8.  
  9.  
  10. #include <streams.h>
  11. #include <limits.h>
  12.  
  13.  
  14.  
  15. // 'this' used in constructor list
  16. #pragma warning(disable:4355)
  17.  
  18.  
  19. STDMETHODIMP CBaseReferenceClock::NonDelegatingQueryInterface(
  20.     REFIID riid,
  21.     void ** ppv) {
  22.     HRESULT hr;
  23.  
  24.     if(riid == IID_IReferenceClock) {
  25.         hr = GetInterface((IReferenceClock *) this, ppv);
  26.     }
  27.     else {
  28.         hr = CUnknown::NonDelegatingQueryInterface(riid, ppv);
  29.     }
  30.     return hr;
  31. }
  32.  
  33. CBaseReferenceClock::~CBaseReferenceClock() {
  34.  
  35.     if(m_TimerResolution) timeEndPeriod(m_TimerResolution);
  36.  
  37.     m_pSchedule->DumpLinkedList();
  38.  
  39.     if(m_hThread) {
  40.         m_bAbort = TRUE;
  41.         TriggerThread();
  42.         WaitForSingleObject(m_hThread, INFINITE);
  43.         EXECUTE_ASSERT(CloseHandle(m_hThread));
  44.         m_hThread = 0;
  45.         EXECUTE_ASSERT(CloseHandle(m_pSchedule->GetEvent()));
  46.         delete m_pSchedule;
  47.     }
  48. }
  49.  
  50. // A derived class may supply a hThreadEvent if it has its own thread that will take care
  51. // of calling the schedulers Advise method.  (Refere to CBaseReferenceClock::AdviseThread()
  52. // to see what such a thread has to do.)
  53. CBaseReferenceClock::CBaseReferenceClock( TCHAR *pName, LPUNKNOWN pUnk, HRESULT *phr, CAMSchedule * pShed )
  54. : CUnknown( pName, pUnk )
  55. , m_rtLastGotTime(0)
  56. , m_TimerResolution(0)
  57. , m_bAbort( FALSE )
  58. , m_pSchedule( pShed ? pShed : new CAMSchedule(CreateEvent(NULL, FALSE, FALSE, NULL)) )
  59. , m_hThread(0) {
  60.  
  61.  
  62.     ASSERT(m_pSchedule);
  63.     if(!m_pSchedule) {
  64.         *phr = E_OUTOFMEMORY;
  65.     }
  66.     else {
  67.         // Set up the highest resolution timer we can manage
  68.         TIMECAPS tc;
  69.         m_TimerResolution = (TIMERR_NOERROR == timeGetDevCaps(&tc, sizeof(tc)))
  70.         ? tc.wPeriodMin : 1;
  71.  
  72.         timeBeginPeriod(m_TimerResolution);
  73.  
  74.         /* Initialise our system times - the derived clock should set the right values */
  75.         m_dwPrevSystemTime = timeGetTime();
  76.         m_rtPrivateTime = (UNITS / MILLISECONDS) * m_dwPrevSystemTime;
  77.  
  78. #ifdef PERF
  79.         m_idGetSystemTime = MSR_REGISTER(TEXT("CBaseReferenceClock::GetTime"));
  80. #endif
  81.  
  82.         if(!pShed) {
  83.             DWORD ThreadID;
  84.             m_hThread = ::CreateThread(NULL,                  // Security attributes
  85.                 (DWORD) 0,             // Initial stack size
  86.                 AdviseThreadFunction,  // Thread start address
  87.                 (LPVOID) this,         // Thread parameter
  88.                 (DWORD) 0,             // Creation flags
  89.                 &ThreadID);            // Thread identifier
  90.  
  91.             if(m_hThread) {
  92.                 SetThreadPriority(m_hThread, THREAD_PRIORITY_TIME_CRITICAL);
  93.             }
  94.             else {
  95.                 *phr = E_FAIL;
  96.                 EXECUTE_ASSERT(CloseHandle(m_pSchedule->GetEvent()));
  97.                 delete m_pSchedule;
  98.             }
  99.         }
  100.     }
  101. }
  102.  
  103. STDMETHODIMP CBaseReferenceClock::GetTime(REFERENCE_TIME *pTime) {
  104.     HRESULT hr;
  105.     if(pTime) {
  106.         REFERENCE_TIME rtNow;
  107.         Lock();
  108.         rtNow = GetPrivateTime();
  109.         if(rtNow > m_rtLastGotTime) {
  110.             m_rtLastGotTime = rtNow;
  111.             hr = S_OK;
  112.         }
  113.         else {
  114.             hr = S_FALSE;
  115.         }
  116.  
  117.         *pTime = m_rtLastGotTime;
  118.         Unlock();
  119.         MSR_INTEGER(m_idGetSystemTime, LONG((*pTime) / (UNITS/MILLISECONDS)));
  120.     }
  121.     else hr = E_POINTER;
  122.  
  123.     return hr;
  124. }
  125.  
  126. /* Ask for an async notification that a time has elapsed */
  127.  
  128. STDMETHODIMP CBaseReferenceClock::AdviseTime(
  129.     REFERENCE_TIME baseTime,         // base reference time
  130.     REFERENCE_TIME streamTime,       // stream offset time
  131.     HEVENT hEvent,                  // advise via this event
  132.     DWORD_PTR *pdwAdviseCookie)         // where your cookie goes
  133. {
  134.     CheckPointer(pdwAdviseCookie, E_POINTER);
  135.     *pdwAdviseCookie = 0;
  136.  
  137.     // Check that the event is not already set
  138.     ASSERT(WAIT_TIMEOUT == WaitForSingleObject(HANDLE(hEvent),0));
  139.  
  140.     HRESULT hr;
  141.  
  142.     const REFERENCE_TIME lRefTime = baseTime + streamTime;
  143.     if(lRefTime <= 0 || lRefTime == MAX_TIME) {
  144.         hr = E_INVALIDARG;
  145.     }
  146.     else {
  147.         *pdwAdviseCookie = m_pSchedule->AddAdvisePacket(lRefTime, 0, HANDLE(hEvent), FALSE);
  148.         hr = *pdwAdviseCookie ? NOERROR : E_OUTOFMEMORY;
  149.     }
  150.     return hr;
  151. }
  152.  
  153.  
  154. /* Ask for an asynchronous periodic notification that a time has elapsed */
  155.  
  156. STDMETHODIMP CBaseReferenceClock::AdvisePeriodic(
  157.     REFERENCE_TIME StartTime,         // starting at this time
  158.     REFERENCE_TIME PeriodTime,        // time between notifications
  159.     HSEMAPHORE hSemaphore,           // advise via a semaphore
  160.     DWORD_PTR *pdwAdviseCookie)          // where your cookie goes
  161. {
  162.     CheckPointer(pdwAdviseCookie, E_POINTER);
  163.     *pdwAdviseCookie = 0;
  164.  
  165.     HRESULT hr;
  166.     if(StartTime > 0 && PeriodTime > 0 && StartTime != MAX_TIME) {
  167.         *pdwAdviseCookie = m_pSchedule->AddAdvisePacket(StartTime, PeriodTime, HANDLE(hSemaphore), TRUE);
  168.         hr = *pdwAdviseCookie ? NOERROR : E_OUTOFMEMORY;
  169.     }
  170.     else hr = E_INVALIDARG;
  171.  
  172.     return hr;
  173. }
  174.  
  175.  
  176. STDMETHODIMP CBaseReferenceClock::Unadvise(DWORD_PTR dwAdviseCookie) {
  177.     return m_pSchedule->Unadvise(dwAdviseCookie);
  178. }
  179.  
  180.  
  181. REFERENCE_TIME CBaseReferenceClock::GetPrivateTime() {
  182.     CAutoLock cObjectLock(this);
  183.  
  184.  
  185.     /* If the clock has wrapped then the current time will be less than
  186.     * the last time we were notified so add on the extra milliseconds
  187.     *
  188.     * The time period is long enough so that the likelihood of
  189.     * successive calls spanning the clock cycle is not considered.
  190.     */
  191.  
  192.     DWORD dwTime = timeGetTime(); {
  193.         m_rtPrivateTime += Int32x32To64(UNITS / MILLISECONDS, (DWORD)(dwTime - m_dwPrevSystemTime));
  194.         m_dwPrevSystemTime = dwTime;
  195.     }
  196.  
  197.     return m_rtPrivateTime;
  198. }
  199.  
  200.  
  201. /* Adjust the current time by the input value.  This allows an
  202.    external time source to work out some of the latency of the clock
  203.    system and adjust the "current" time accordingly.  The intent is
  204.    that the time returned to the user is synchronised to a clock
  205.    source and allows drift to be catered for.
  206.  
  207.    For example: if the clock source detects a drift it can pass a delta
  208.    to the current time rather than having to set an explicit time.
  209. */
  210.  
  211. STDMETHODIMP CBaseReferenceClock::SetTimeDelta(const REFERENCE_TIME & TimeDelta) {
  212. #ifdef DEBUG
  213.  
  214.     // Just break if passed an improper time delta value
  215.     LONGLONG llDelta = TimeDelta > 0 ? TimeDelta : -TimeDelta;
  216.     if(llDelta > UNITS * 1000) {
  217.         DbgLog((LOG_TRACE, 0, TEXT("Bad Time Delta")));
  218.         DebugBreak();
  219.     }
  220.  
  221.     // We're going to calculate a "severity" for the time change. Max -1
  222.     // min 8.  We'll then use this as the debug logging level for a
  223.     // debug log message.
  224.     const LONG usDelta = LONG(TimeDelta/10);      // Delta in micro-secs
  225.  
  226.     DWORD delta        = abs(usDelta);            // varying delta
  227.     // Severity == 8 - ceil(log<base 8>(abs( micro-secs delta)))
  228.     int   Severity     = 8;
  229.     while(delta > 0) {
  230.         delta >>= 3;                              // div 8
  231.         Severity--;
  232.     }
  233.  
  234.     // Sev == 0 => > 2 second delta!
  235.     DbgLog((LOG_TIMING, Severity < 0 ? 0 : Severity,
  236.     TEXT("Sev %2i: CSystemClock::SetTimeDelta(%8ld us) %lu -> %lu ms."),
  237.     Severity, usDelta, DWORD(ConvertToMilliseconds(m_rtPrivateTime)),
  238.     DWORD(ConvertToMilliseconds(TimeDelta+m_rtPrivateTime)) ));
  239.  
  240.     // Don't want the DbgBreak to fire when running stress on debug-builds.
  241. #ifdef BREAK_ON_SEVERE_TIME_DELTA
  242.     if(Severity < 0)
  243.         DbgBreakPoint(TEXT("SetTimeDelta > 16 seconds!"),
  244.             TEXT(__FILE__),__LINE__);
  245. #endif
  246.  
  247. #endif
  248.  
  249.     CAutoLock cObjectLock(this);
  250.     m_rtPrivateTime += TimeDelta;
  251.     // If time goes forwards, and we have advises, then we need to
  252.     // trigger the thread so that it can re-evaluate its wait time.
  253.     // Since we don't want the cost of the thread switches if the change
  254.     // is really small, only do it if clock goes forward by more than
  255.     // 0.5 millisecond.  If the time goes backwards, the thread will
  256.     // wake up "early" (relativly speaking) and will re-evaluate at
  257.     // that time.
  258.     if(TimeDelta > 5000 && m_pSchedule->GetAdviseCount() > 0) TriggerThread();
  259.     return NOERROR;
  260. }
  261.  
  262. // Thread stuff
  263.  
  264. DWORD __stdcall CBaseReferenceClock::AdviseThreadFunction(LPVOID p) {
  265.     return DWORD(reinterpret_cast<CBaseReferenceClock*>(p)->AdviseThread());
  266. }
  267.  
  268. HRESULT CBaseReferenceClock::AdviseThread() {
  269.     DWORD dwWait = INFINITE;
  270.  
  271.     // The first thing we do is wait until something interesting happens
  272.     // (meaning a first advise or shutdown).  This prevents us calling
  273.     // GetPrivateTime immediately which is goodness as that is a virtual
  274.     // routine and the derived class may not yet be constructed.  (This
  275.     // thread is created in the base class constructor.)
  276.  
  277.     while(!m_bAbort) {
  278.         // Wait for an interesting event to happen
  279.         DbgLog((LOG_TIMING, 3, TEXT("CBaseRefClock::AdviseThread() Delay: %lu ms"), dwWait ));
  280.         WaitForSingleObject(m_pSchedule->GetEvent(), dwWait);
  281.         if(m_bAbort) break;
  282.  
  283.         // There are several reasons why we need to work from the internal
  284.         // time, mainly to do with what happens when time goes backwards.
  285.         // Mainly, it stop us looping madly if an event is just about to
  286.         // expire when the clock goes backward (i.e. GetTime stop for a
  287.         // while).
  288.         const REFERENCE_TIME  rtNow = GetPrivateTime();
  289.  
  290.         DbgLog((LOG_TIMING, 3,
  291.             TEXT("CBaseRefClock::AdviseThread() Woke at = %lu ms"),
  292.             ConvertToMilliseconds(rtNow) ));
  293.  
  294.         // We must add in a millisecond, since this is the resolution of our
  295.         // WaitForSingleObject timer.  Failure to do so will cause us to loop
  296.         // franticly for (approx) 1 a millisecond.
  297.         m_rtNextAdvise = m_pSchedule->Advise(10000 + rtNow);
  298.         LONGLONG llWait = m_rtNextAdvise - rtNow;
  299.  
  300.         ASSERT(llWait > 0);
  301.  
  302.         llWait = ConvertToMilliseconds(llWait);
  303.         // DON'T replace this with a max!! (The type's of these things is VERY important)
  304.         dwWait = (llWait > REFERENCE_TIME(UINT_MAX)) ? UINT_MAX : DWORD(llWait);
  305.     };
  306.     return NOERROR;
  307. }
  308.  
  309.